<template>
  <div id="app" v-bind:style="appDivStyle">
      <div class="context" ref="context">
           <div class="queryBox" ref="queryBox">
                <el-form :model="formQueryCondition"
                         ref="form" size="mini">
                    <el-row>
                        <!-- 专区名称 -->
                        <el-col :span="5">
                            <el-form-item :label="$t('SpecialArea.queryLabel.specialAreaCode')"   :label-width="queryformLabelWidth">
                                <el-input v-model.trim="formQueryCondition.speAreaCode.val" class="queryItemStyle" clearable
                                        :placeholder="$t('SpecialArea.queryLabel.placeholderSpecialAreaCode')">
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <!-- 专区编码 -->
                        <el-col :span="5" :offset="1">
                            <el-form-item :label="$t('SpecialArea.queryLabel.specialAreaName')"   :label-width="queryformLabelWidth">
                                <el-input v-model.trim="formQueryCondition.speAreaName.val" class="queryItemStyle" clearable
                                        :placeholder="$t('SpecialArea.queryLabel.placeholderSpecialAreaName')">
                                </el-input>
                            </el-form-item>
                        </el-col>
                            <!-- <el-form-item :label="$t('SpecialArea.queryLabel.status')"  :label-width="queryformLabelWidth">
                                <el-select v-model="formQueryCondition.status.val" class="queryItemStyle">
                                    <el-option :label="$t('label.all')" value=""></el-option>
                                    <el-option :label="$t('label.available')" value="Available"></el-option>
                                    <el-option :label="$t('label.invalid')" value="Invalid"></el-option>
                                </el-select>
                            </el-form-item> -->
                            <!-- 状态 -->
                        <el-col :span="5" :offset="1">
                            <el-form-item :label="$t('Dictionary.queryLabel.status')"  :label-width="queryformLabelWidth">
                                <el-select v-model="formQueryCondition.isEnable.val" class="queryItemStyle">
                                    <el-option :label="$t('label.all')" value=""></el-option>
                                    <el-option :value="drug.valueCode" :key="drug.valueCode" :label="drug.valueText"
                                        v-for="drug in enables"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <!-- 列表上的按钮 -->
                    <el-row>
                        <el-col :span="24">
                            <div style="text-align:right">
                                <el-form-item>
                                    <!-- 新增 -->
                                    <el-button v-permission="{menuCode: menuCode, resourceCode: 'saveBtnText'}" type="primary" v-if="test('onNewBtn')" @click="onNew('saveBtnText')">{{ $t('btnText.newBtnText') }}</el-button>
                                <!-- </el-form-item> -->
                                <!-- <el-form-item> -->
                                    <!-- 重置 -->
                                    <el-button v-permission="{menuCode: menuCode, resourceCode: 'resetBtnText'}" type="primary" @click="onReset('form')">{{ $t('btnText.resetBtnText') }}</el-button>
                                <!-- </el-form-item> -->
                                <!-- <el-form-item>
                                    <el-button type="primary" @click="onExport" icon="el-icon-download" :loading="loading">{{ $t('btnText.exportBtnText') }}</el-button>
                                </el-form-item> -->
                                <!-- <el-form-item> -->
                                     <!-- 查询 -->
                                    <el-button v-permission="{menuCode: menuCode, resourceCode: 'queryBtnText'}" type="primary" @click="onQuery('queryBtnText')" icon="el-icon-search" :loading="loading">{{ $t('btnText.queryBtnText') }}</el-button>
                                </el-form-item>
                            </div>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
            <div class="dataBox" ref="dataBox">

                <transition enter-active-class="animated zoomIn" leave-active-class="animated rotateOut">
                    <el-table v-if="isInit" ref="singleTable"
                                :data="tableData"
                                :height="tableHeight"
                                @sort-change="sortChange"
                                v-loading="loading" size="mini"
                                style="width: 100%;" stripe=stripe border=border>
                        <el-table-column type="index"  width="50" fixed="left"
                                            :label="$t('table.xh')" align="center">
                        </el-table-column>
                        <el-table-column :label="$t('table.op')" fixed="left" min-width="200">
                            <template slot-scope="scope">
                                <el-button v-permission="{menuCode: menuCode, resourceCode: 'editBtnText'}" size="gv" icon="el-icon-edit" :loading="loading"
                                @click="edit(scope.$index, scope.row,'editBtnText')"
                                            >{{ $t('btnText.editBtnText') }}</el-button>
                                <!--下发-->
                                <el-button size="gv" icon="el-icon-delete"
                                    v-permission="{menuCode: menuCode, resourceCode: 'sendBtnText'}"
                                        type="danger" :loading="loading" @click="onSend(scope.$index, scope.row,'sendBtnText')"
                                        :disabled="scope.row.sendtoState!='StayDown'" >{{ $t('ParentAssetIssuance.btnText.sendBtnText') }}</el-button>
                                <!-- 注销 -->
                                <el-button size="gv" icon="el-icon-delete" v-show="scope.row.isEnable=='Available'" v-permission="{menuCode: menuCode,resourceCode: 'passBtnText'}"
                                      type="danger" :loading="loading" @click="logoffRow(scope.$index, scope.row,'passBtnText')"
                                     >{{ $t('btnText.logoffBtnText') }}</el-button>
                                <!-- 恢复 -->
                                <el-button size="gv" icon="el-icon-delete" v-show="scope.row.isEnable==='Invalid'"
                                v-permission="{menuCode: menuCode,resourceCode: 'recoveryBtnText'}"
                                      type="danger" :loading="loading" @click="revertLogoffRow(scope.$index, scope.row,'recoveryBtnText')"
                                     >{{ $t('btnText.recoveryBtnText') }}</el-button>
                                <!-- 删除 -->
                                <el-button size="gv" icon="el-icon-delete" v-show="scope.row.isEnable==='Invalid'"
                                v-permission="{menuCode: menuCode,resourceCode: 'delBtnText'}"
                                    type="danger" :loading="loading" @click="deleteRow(scope.$index, scope.row,'delBtnText')"
                                    >{{ $t('btnText.deleteBtnText') }}</el-button>
                            </template>
                        </el-table-column>
                        <el-table-column prop="speAreaCode" min-width="140" fixed="left"
                                            :label="$t('SpecialArea.table.specialAreaCode')" sortable="custom" sort-by="speAreaCode">
                        </el-table-column>
                        <el-table-column prop="speAreaName" min-width="140" fixed="left"
                                            :label="$t('SpecialArea.table.specialAreaName')" sortable="custom" sort-by="speAreaName">
                        </el-table-column>
                        <el-table-column prop="remark" min-width="140"
                                            :label="$t('SpecialArea.table.desc')" sortable="custom" sort-by="remark">
                        </el-table-column>
                        <!--下发状态-->
                    <el-table-column prop="sendtoStateName" min-width="110"
                                        :label="$t('ParentAssetIssuance.table.ParentAssetIssuance.status')" sortable="custom" sort-by="sendtoState">
                    </el-table-column>
                        <el-table-column prop="isEnableName" min-width="110" sortable="custom"
                        :label="$t('SpecialArea.table.status')" sort-by="isEnable">
                        </el-table-column>

                        <el-table-column :label="$t('SpecialArea.table.lastUpdatedBy')" min-width="120" sortable="custom" prop="modifier" sort-by="modifier">
                        </el-table-column>
                        <el-table-column :label="$t('SpecialArea.table.lastUpdateTime')" min-width="180" sortable="custom" prop="lastUpdatedDate" sort-by="lastUpdatedDate">
                        </el-table-column>

                    </el-table>
                </transition>

            </div>
        </div>
        <div class="pageBox">
            <el-pagination @size-change="sizeChange"
                            @current-change="currentPageChange"
                            :current-page="pager.curPage"
                            :page-sizes="pager.sizes"
                            :page-size="pager.curSize"
                            :background="true"
                            layout="total, sizes, prev, pager, next, jumper" :total="pager.total">
            </el-pagination>
        </div>

         <!--编辑对话框-->
        <transition enter-active-class="animated rotateIn" leave-active-class="animated rotateOut">
            <el-dialog :title="$t('label.dialogTitle')" :visible.sync="isShowEditForm" top="5vh" :close-on-click-modal="false">
                <el-form :model="editForm" ref="editForm" size="mini"
                        :label-position="editFormPosition" status-icon=status-icon :rules="editRules">
                    <el-form-item :label="$t('SpecialArea.editLabel.specialAreaCode')"
                        :label-width="editformLabelWidth" prop="speAreaCode">
                        <el-input v-model.trim="editForm.speAreaCode" maxlength="20" :disabled="canEditCode"
                                :placeholder="$t('SpecialArea.editLabel.placeholderSpecialAreaCode')"></el-input>
                    </el-form-item>
                    <el-form-item :label="$t('SpecialArea.editLabel.specialAreaName')"
                        :label-width="editformLabelWidth" prop="speAreaName">
                        <el-input v-model.trim="editForm.speAreaName" maxlength="50"
                                :placeholder="$t('SpecialArea.editLabel.placeholderSpecialAreaName')"></el-input>
                    </el-form-item>

                    <el-form-item :label="$t('SpecialArea.editLabel.desc')"
                        :label-width="editformLabelWidth" prop="remark">
                        <el-input v-model="editForm.remark" maxlength="100" type="textarea"
                                :placeholder="$t('SpecialArea.editLabel.placeholderDesc')"></el-input>
                    </el-form-item>

                    <el-form-item :label="$t('Dictionary.queryLabel.status')"  :label-width="editformLabelWidth">
                        <el-select v-model="editForm.isEnable" class="queryItemStyle">
                            <el-option :value="drug.valueCode" :key="drug.valueCode" :label="drug.valueText" v-for="drug in enables"></el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
                <div slot="footer">
                    <el-button size="mini" @click="isShowEditForm = false" :loading="loading">{{ $t('btnText.cancelBtnText') }}</el-button>
                    <el-button size="mini" type="primary" @click="submitForm('editForm',currentResCode)" :loading="loading">{{ $t('btnText.saveBtnText') }}</el-button>
                </div>
            </el-dialog>
        </transition>

  </div>


</template>

<script>

import comBaseVue from '../../baseViewModel';

export default {
  mixins: [comBaseVue],
  name:'SpecialArea',
  props: {
    menuCode: String
  },
  data () {

    return {
        queryformLabelWidthLong:"110px",
        isInit:false,
        tableHeight:100,
        appDivStyle:{
            height:this.$store.getters.appHeight,
        },
         //下发
        sendForm: {
            siteList: [],//下发到的站点
            sendType:"",
        },
        enables: [],
        exsitFlag: false,
        opType: "",
        modelName:"com.ispr.iptv.entity.sys.SpeArea",
        // 查询条件
        formQueryCondition: {
            speAreaCode: {
                key: 'speAreaCode',
                //mapName: 'code.key',  映射的别名 在同时查询一个属性时需要别名
                //gName:'code',   组名
                op: 'LIKE', // 操作符
                val: '' // 查询的值
            },
            speAreaName: {
                key: 'speAreaName',
                //mapName: 'code.key',  映射的别名 在同时查询一个属性时需要别名
                //gName:'code',   组名
                op: 'LIKE', // 操作符
                val: '' // 查询的值
            },
            isEnable: {
                key: 'isEnable',
                op: '=', // 操作符
                val: 'Available'
            },
        },

        // 编辑面板绑定的对象
        editForm: {
            keyId: 0,
            version: 0,
            speAreaCode: "",
            speAreaName: "",
            remark: "",
            sendtoState: "StayDown",
            isEnable: "Available",
        },
        // 编辑面板的验证规则
        editRules: {
            speAreaCode: [{ required: true, message: this.$i18n.t('SpecialArea.rules.placeholderSpecialAreaCode'), trigger: 'blur' }],
            speAreaName: [{ required: true, message: this.$i18n.t('SpecialArea.rules.placeholderSpecialAreaName'), trigger: 'blur' }],
            remark: [{ required: false, message: this.$i18n.t('SpecialArea.rules.placeholderDesc'), trigger: 'blur' }],
        },
    }
  },
  methods:{
      test:function(btnCode){
          return true;
        },
    // 新增
    onNew: function(rescode) {
        this.currentResCode = (rescode && rescode!=='') ? rescode : '';
        this.opType = "new";
        this.isShowEditForm = true;
        if (this.$refs['editForm']) {
            this.$refs['editForm'].resetFields();
        }
        this.editForm.keyId = "";
        this.editForm.version = "";
        this.editForm.speAreaCode = "";
        this.editForm.speAreaName = "";
        this.editForm.remark = "";
        this.editForm.sendtoState = "StayDown";
        this.editForm.isEnable = "Available";
        this.curCommand = "SaveSpeAreaProc";
        this.canEditCode = false;
    },

     // 重置
    onReset:function(){
        if (this.$refs['form']) {
            this.$refs['form'].resetFields();
        }
        this.formQueryCondition.speAreaCode.val = "";
        this.formQueryCondition.speAreaName.val = "";
        this.formQueryCondition.isEnable.val = "Available";
    },
    //单个下发
    onSend: function(index, row, rescode) {

        var _this = this;
        this.currentResCode = (rescode && rescode!=='') ? rescode : '';
        this.sendForm.sendType = "single";
        this.singleSend = {};
        let data = {
          "keyId":row.keyId,
          "version":row.version,
          "resType":"AREA",
        };
        let dataList = [];//最终传给后台的总数据
        dataList.push(data);
        this.$confirm(this.$i18n.t("message.confirmSendMessage"),
            this.$i18n.t("message.confirmTitle"), {
            confirmButtonText: this.$i18n.t("message.yes"),
            cancelButtonText: this.$i18n.t("message.cancel"),
            type: "warning",
            callback: function (action, instance) {
                if (action == "confirm") {
                    _this.loading = true;
                    _this.procCommand("MediaSendToProc",
                    _this.modelName,
                    "Default",
                    {
                      "dataList":dataList,
                    },
                    null,
                    _this.submitFormCallback);
                }
            }
        });
    },

    // 删除按钮
    deleteRow:function(index, row, rescode){
        this.currentResCode = (rescode && rescode!=='') ? rescode : '';
        var _this = this;
        this.$confirm(this.$i18n.t("message.confirmDelMessage"),
            this.$i18n.t("message.confirmTitle"), {
            confirmButtonText: this.$i18n.t("message.yes"),
            cancelButtonText: this.$i18n.t("message.cancel"),
            type: "warning",
            callback: function (action, instance) {
                if (action == "confirm") {
                    var commandBody = {"keyId": row.keyId, "version": row.version};
                    _this.loading = true;
                    _this.procCommand("SpecialDelProc",
                            _this.modelName,
                            "N",
                            commandBody,
                            null,
                            _this.submitFormCallback);
                }

            }
        });
    },

    //恢复按钮
    recovery: function(index, row,rescode) {
        this.currentResCode = (rescode && rescode!=='') ? rescode : '';
        var _this = this;
        this.$confirm(this.$i18n.t("message.confirmRevertLogoffMessage"),
            this.$i18n.t("message.confirmTitle"), {
            confirmButtonText: this.$i18n.t("message.yes"),
            cancelButtonText: this.$i18n.t("message.cancel"),
            type: "warning",
            callback: function (action, instance) {
                if (action == "confirm") {
                    var commandBody = {  "keyId": row.keyId, "version": row.version, isEnable: "Available" };
                    _this.loading = true;
                    _this.procCommand("UpdateSpeAreaProc",
                            _this.modelName,
                            "default",
                            commandBody,
                            null,
                            _this.submitFormCallback);
                }

            }
        });
    },

    // 注销按钮 (同时将用户-专区关系表相对应的数据修改成不可用)
    async logoffRow(index, row, rescode) {
        this.currentResCode = (rescode && rescode!=='') ? rescode : '';
        var _this = this;
        let tip = "";
        await this.querySpeArea(row.keyId);
        if(this.exsitFlag){
            tip = this.$i18n.t("message.confirmSpeAreaLogoffMessage");
        }else{
            tip = this.$i18n.t("message.confirmlogoffMessage");
        }
        this.$confirm(tip,
            this.$i18n.t("message.confirmTitle"), {
            confirmButtonText: this.$i18n.t("message.yes"),
            cancelButtonText: this.$i18n.t("message.cancel"),
            type: "warning",
            callback: function (action, instance) {
                if (action == "confirm") {
                    var commandBody = {  "keyId": row.keyId, "version": row.version, isEnable: "Invalid", sendtoState:"StayDown" };
                    _this.loading = true;
                    _this.procCommand("PassProc",//"ChangeIsEnabledState",
                            _this.modelName,
                            "N",
                            commandBody,
                            null,
                            _this.submitFormCallback);
                }

            }
        });
    },
        // 恢复注销按钮
        revertLogoffRow: function(index, row, rescode) {
            this.currentResCode = (rescode && rescode!=='') ? rescode : '';
            var _this = this;
            this.$confirm(this.$i18n.t("message.confirmNormalMessage"),
                this.$i18n.t("message.confirmTitle"), {
                confirmButtonText: this.$i18n.t("message.yes"),
                cancelButtonText: this.$i18n.t("message.cancel"),
                type: "warning",
                callback: function (action, instance) {
                    if (action == "confirm") {
                        var commandBody = {  "keyId": row.keyId, "version": row.version, isEnable: "Available", sendtoState:"StayDown" };
                        _this.loading = true;
                        _this.procCommand("RecoveryProc",
                                _this.modelName,
                                "N",
                                commandBody,
                                null,
                                _this.submitFormCallback);
                    }

                }
            });
        },

    validateItem: function(params){
        let requestArgs = {
            className: this.modelName,
            opKey: "byId",
            params: params,
            userInfo: this.getUserInfo()
        };
        let _this =  this;
        return new Promise((resolve, reject) => {
            _this.axios.post('/api/query', requestArgs, {headers: this.headersObj})
            .then(function(res) {

                  if (res.data.code == "SUCCESS") {
                    if(res.data.data.length != 0){
                      _this.existFlag = true;
                    }else{
                      _this.existFlag = false;
                    }
                  } else {
                      _this.$message.error(this.$i18n.t("Capital.label.errorMessage"));
                  }
                  resolve(_this.existFlag);
            })
            .catch(function(error) {
                console.log(error);
            });
        });

    },

    querySpeArea: function(speAreaId){
        var _this = this;
        var queryRequest = {
            className: "com.ispr.iptv.entity.sys.UserSpeAreaEntity",
            opKey: "Query",
            params: [
                {"key":"isEnable","op":"=","val":"Available"},
                {"key":"speAreaId","op":"=","val":speAreaId},
            ],
            userInfo: this.getUserInfo()
        };
        //查询可以授权的所有角色信息
        return new Promise((resolve, reject)=>{
            this.axios.post('/api/query', queryRequest, {headers: this.headersObj})
                .then(function(res) {
                    if (res.data.code == "SUCCESS") {
                       if(res.data.data.length != 0){
                           _this.exsitFlag = true;
                       }else{
                           _this.exsitFlag = false;
                       }
                    } else {
                        _this.$message.error("数据查询异常");
                    }
                    resolve(_this.exsitFlag);
                })
                .catch(function(error) {
                    console.log(error);
                    _this.$message.error(error);
                });
        });
    },

    // 授权按钮单击事件
    editMenu: function(index, row) {

    },

    // 编辑按钮单击事件
    edit: function(index, row, rescode){
        this.currentResCode = (rescode && rescode!=='') ? rescode : '';
        this.opType = "update";
        //dataAccess.queryDomainModelByKeyID(this, modelName, "Query", row.keyID, true, this.$options.methods.editCallback);
        this.queryModelByKeyID(this.modelName,row.keyId,"byId",this.editCallback);
    },

    // 编辑按钮回调事件
    editCallback: function(isSuccess,json) {
    //   debugger
        if(isSuccess){
            this.curCommand = "UpdateSpeAreaProc";
            this.isShowEditForm = true;
            if (this.$refs['editForm']) {
                this.$refs['editForm'].resetFields();
            }
            // this.editForm = json;
            this.editForm.keyId = json.keyId;
            this.editForm.version = json.version;
            this.editForm.speAreaCode = json.speAreaCode;
            this.editForm.speAreaName = json.speAreaName;
            this.editForm.remark = json.remark;
            this.editForm.sendtoState = "StayDown";
            // this.editForm.sitStatus = json.sitStatus;
            this.editForm.isEnable = json.isEnable;
            this.canEditCode = true;
        }
        else{
            this.$message({
                message: json.msg,
                type: 'warning'
                });
        }
    },

    // 为状态下拉框赋值
    findEnables: function() {
        this.findByTypeCode("10001",this.setEnables)
    },
    // 查询状态下拉框数据成功后的回调
    setEnables: function(isSuccess,json) {
        try{
            if (isSuccess) {
                this.enables = [];
                for (var i = 0; i < json.data.length; i++) {
                    this.enables.push(json.data[i]);
                }
            }
            else {
                this.$message.error(json.msg);
            }
        }
        catch(e){
            alert(e);
        }
    },
     //编辑面板提交后调用，设置唯一性验证条件
    setEditFormCheck:function setEditFormCheck(){
    //   debugger
        if(this.curCommand == "SaveSpeAreaProc"){
            this.editFormCheck = [{
                    key: 'speAreaCode',
                    op: '=', // 操作符
                    val: this.editForm.speAreaCode// 查询的值
                },{
                    key: 'isEnable',
                    op: '=', // 操作符
                    val: 'Available'
                }];
        }else if(this.curCommand == "UpdateSpeAreaProc"){
            this.editFormCheck = [{
                    key: 'speAreaCode',
                    op: '=', // 操作符
                    val: this.editForm.speAreaCode// 查询的值
                },{
                    key: 'isEnable',
                    op: '=', // 操作符
                    val: 'Available'
                },{
                    key: 'keyId',
                    op: '<>', // 操作符
                    val: this.editForm.keyId
                }];
        }

    },

    // 提交编辑面板数据
    async submitForm(formName, rescode){
        this.currentResCode = (rescode && rescode!=='') ? rescode : '';
        var _this = this;
        let params = [];
        if(this.opType == "new"){
            params = [
              {key: 'speAreaCode',op: '=',val: this.editForm.speAreaCode},
            //   {key: 'isEnable',op: '=',val: "Available"}
            ]
        }else if(this.opType == "update"){
            params = [
              {key: 'speAreaCode',op: '=',val: this.editForm.speAreaCode},
              {key: 'keyId',op: '<>',val: this.editForm.keyId},
            //   {key: 'isEnable',op: '=',val: "Available"}
            ]
        }
        await this.validateItem(params);
        if(this.existFlag){
            this.$message.warning("专区编码"+_this.editForm.speAreaCode+"已存在");
            return;
        }

        params = [];
        if(this.opType == "new"){
            params = [
              {key: 'speAreaName',op: '=',val: this.editForm.speAreaName},
              {key: 'isEnable',op: '=',val: "Available"}
            ]
        }else if(this.opType == "update"){
            params = [
              {key: 'speAreaName',op: '=',val: this.editForm.speAreaName},
              {key: 'keyId',op: '<>',val: this.editForm.keyId},
              {key: 'isEnable',op: '=',val: "Available"}
            ]
        }
        await this.validateItem(params);
        if(this.existFlag){
            this.$message.warning("专区名称"+this.editForm.speAreaName+"已存在");
            return;
        }else{
            this.$refs['editForm'].validate(function (valid) {
              if (valid) {
                  _this.loading = true;
                  _this.procCommand(_this.curCommand,
                  _this.modelName,
                  "Default",
                  _this.editForm,
                  // _this.editFormCheck,
                  null,
                  _this.submitFormCallback);
              } else {
                  return false;
              }
            });
        }


    },

    initTable:function(){
        this.tableHeight = this.$refs.context.offsetHeight - this.$refs.queryBox.offsetHeight;
        this.isInit = true;
    },
      enterDown(){
          var g = this
          if(g.isShowEditForm){
              g.submitForm('editForm',g.currentResCode)
          }else if(!g.loading){
              g.onQuery()
          }
      }


  },
  mounted: function mounted() {
    this.findEnables();
    this.onQuery();
    window.setTimeout(this.initTable,100);
  }
}


</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

</style>
